package bin_tree.leetcode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author yuisama
 * @date 2023/03/27 20:03
 * 后序遍历
 **/
public class Num145_PostOrder {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        // 当前即将要访问的节点
        TreeNode cur = root;
        // 上一个完全访问结束的节点
        TreeNode prev = null;
        Deque<TreeNode> stack = new LinkedList<>();
        while (cur != null || !stack.isEmpty()) {
            // 先一路向左
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            if (cur.right == null || prev == cur.right) {
                // 右子树为空或者已经访问结束
                result.add(cur.val);
                // 更新prev为当前节点
                prev = cur;
//                // 将cur置空，下一次循环从栈顶取元素
//                cur = null;
            }else {
                // 继续访问右子树
                stack.push(cur);
                cur = cur.right;
            }
        }
        return result;
    }
}